package com.example.demo.config;

import cn.hutool.core.util.StrUtil;
import com.example.demo.pojo.Result;
import com.example.demo.pojo.exception.SystemException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常处理
 *
 * @author TongDaShuai
 * @since 2021/8/20
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(value = SystemException.class)
    @ResponseBody
    public Result sysErrorHandler(HttpServletRequest req, Exception e)  {
        log.error(StrUtil.format("接口（{}）出现异常信息", req.getRequestURI()), e);
        return Result.error(e.getMessage());
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseBody
    public Result argumentValidHandler(HttpServletRequest req, Exception e)  {
        log.error(StrUtil.format("接口（{}）出现参数校验异常信息", req.getRequestURI()), e);
        BindingResult bindingResult = ((MethodArgumentNotValidException) e).getBindingResult();
        String errorMesssage = "参数校验异常:";
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            errorMesssage += fieldError.getDefaultMessage();
            break;
        }
        return Result.error(errorMesssage);
    }

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result defaultErrorHandler(HttpServletRequest req, Exception e)  {
        log.error(StrUtil.format("接口（{}）出现异常信息", req.getRequestURI()), e);
        return Result.error(e.getMessage());
    }
}
